<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */


namespace app\custom;
use think\facade\Db;
class Sxpay
{
	//创建微支付 微信公众号
	public static function build_mp($aid,$bid,$mid,$title,$ordernum,$price,$tablename,$notify_url='',$repeat=0){
		if(!$notify_url) $notify_url = PRE_URL.'/notify.php';
		$member = Db::name('member')->where('id',$mid)->find();
		$package = array();
		$appinfo = \app\common\System::appinfo($aid,'mp');
		$isbusinesspay = false;
		if($bid > 0){
			$business = Db::name('business')->where('id',$bid)->find();
			if($business['sxpay_mno']){
				$appinfo['sxpay_mno'] = $business['sxpay_mno'];
				$appinfo['sxpay_mchkey'] = $business['sxpay_mchkey'];
				$isbusinesspay = true;
			}
		}
		if(!$appinfo['sxpay_mno']){
			return ['status'=>0,'msg'=>'请设置商户编号'];
		}
		if(!$appinfo['sxpay_mchkey']){
			return ['status'=>0,'msg'=>'请设置支付密钥'];
		}

		$appid = $appinfo['appid'];
		$openid = $member[platform.'openid'];
		
		$reqData = [];
		$reqData['mno'] = $appinfo['sxpay_mno']; //商户编号
		$reqData['ordNo'] = $ordernum; //商户订单号
		$reqData['amt'] = $price;
		$reqData['payType'] = 'WECHAT';
		$reqData['payWay'] = '02';
		$reqData['subject'] = $title;
		$reqData['trmIp'] = request()->ip();
		$reqData['subAppid'] = $appid;  //微信子公众号
		$reqData['notifyUrl'] = $notify_url;
		$reqData['userId'] = $openid;
		$reqData['extend'] = $aid.':'.$tablename.':sxpaymp:'.md5($tablename.$ordernum.$appinfo['sxpay_mchkey']);
		if($isbusinesspay) $reqData['extend'] .= ':'.$bid;

		$fenzhang = Db::name('sxpay_fenzhang')->where('aid',$aid)->where('business_code',$reqData['mno'])->where('status',1)->find();
		if($fenzhang){
			$fenzhangdata = json_decode($fenzhang['fenzhangdata'],true);
			if($fenzhangdata){
				$fusruleId = [];
				foreach($fenzhangdata as $fz){
					$fzpercent = floatval($fz['percent']);
					$fzprice = round($fzpercent * 0.01 * $reqData['amt'],2);
					if($fzprice > 0){
						$fusruleId[] = ['allotValue'=>$fzprice,'mno'=>$fz['business_code']];
					}
				}
				if($fusruleId){
					$reqData['fusruleId'] = $fusruleId;
				}
			}
			\think\facade\Log::write($reqData);
		}
		Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['issxpay'=>1,'createtime'=>time()]);

		$rs = self::postapi('build',$reqData,$appinfo['sxpay_mchkey']);
		
		if($rs['code'] != '0000'){
			if($repeat==0 && $rs['code'] == '0002'){
				$newordernum = date('YmdHis').rand(100000,999999);
				Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
				if($tablename == 'shop_hb'){
					Db::name('shop_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					$orderlist = Db::name('shop_order')->where('ordernum','like',$ordernum.'%')->select()->toArray();
					foreach($orderlist as $order){
						$thisordernum = $newordernum.'_'.explode('_',$order['ordernum'])[1];
						Db::name('shop_order')->where('aid',$aid)->where('id',$order['id'])->update(['ordernum'=>$thisordernum]);
						Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['ordernum'=>$thisordernum]);
					}
				}else{
					Db::name($tablename.'_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					if($tablename == 'shop' || $tablename == 'scoreshop' || $tablename == 'restaurant_shop' || $tablename == 'restaurant_booking'){
						Db::name($tablename.'_order_goods')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					}
				}
				return self::build_mp($aid,$bid,$mid,$title,$newordernum,$price,$tablename,$notify_url,1);
			}
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		$respData = $rs['respData'];
		$wOpt = [];
		$wOpt['appId'] = $respData['payAppId'];
		$wOpt['timeStamp'] = $respData['payTimeStamp'];
		$wOpt['nonceStr'] = $respData['paynonceStr'];
		$wOpt['package'] = $respData['payPackage'];
		$wOpt['signType'] = $respData['paySignType'];
		$wOpt['paySign'] = $respData['paySign'];
		
		
		return ['status'=>1,'data'=>$wOpt];
	}
	//创建微支付 微信小程序
	public static function build_wx($aid,$bid,$mid,$title,$ordernum,$price,$tablename,$notify_url=''){
		if(!$notify_url) $notify_url = PRE_URL.'/notify.php';
		$member = Db::name('member')->where('id',$mid)->find();
		$package = array();
		$appinfo = \app\common\System::appinfo($aid,'wx');
		$isbusinesspay = false;
		if($bid > 0){
			$business = Db::name('business')->where('id',$bid)->find();
			if($business['sxpay_mno']){
				$appinfo['sxpay_mno'] = $business['sxpay_mno'];
				$appinfo['sxpay_mchkey'] = $business['sxpay_mchkey'];
				$isbusinesspay = true;
			}
		}
		$appid = $appinfo['appid'];
		$openid = $member[platform.'openid'];
		if(!$appinfo['sxpay_mno']){
			return ['status'=>0,'msg'=>'请设置商户编号'];
		}
		if(!$appinfo['sxpay_mchkey']){
			return ['status'=>0,'msg'=>'请设置支付密钥'];
		}
		
		$reqData = [];
		$reqData['mno'] = $appinfo['sxpay_mno']; //商户编号
		$reqData['ordNo'] = $ordernum; //商户订单号
		$reqData['amt'] = $price;
		$reqData['payType'] = 'WECHAT';
		$reqData['payWay'] = '03';
		$reqData['subject'] = $title;
		$reqData['trmIp'] = request()->ip();
		$reqData['subAppid'] = $appid;  //微信子公众号
		$reqData['notifyUrl'] = $notify_url;
		$reqData['userId'] = $openid;
		$reqData['extend'] = $aid.':'.$tablename.':sxpaywx:'.md5($tablename.$ordernum.$appinfo['sxpay_mchkey']);
		if($isbusinesspay) $reqData['extend'] .= ':'.$bid;

		$fenzhang = Db::name('sxpay_fenzhang')->where('aid',$aid)->where('business_code',$reqData['mno'])->where('status',1)->find();
		if($fenzhang){
			$fenzhangdata = json_decode($fenzhang['fenzhangdata'],true);
			if($fenzhangdata){
				$fusruleId = [];
				foreach($fenzhangdata as $fz){
					$fzpercent = floatval($fz['percent']);
					$fzprice = round($fzpercent * 0.01 * $reqData['amt'],2);
					if($fzprice > 0){
						$fusruleId[] = ['allotValue'=>$fzprice,'mno'=>$fz['business_code']];
					}
				}
				if($fusruleId){
					$reqData['fusruleId'] = $fusruleId;
				}
			}
		}
		//\think\facade\Log::write($reqData);
		Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['issxpay'=>1,'createtime'=>time()]);

		$rs = self::postapi('build',$reqData,$appinfo['sxpay_mchkey']);

		if($rs['code'] != '0000'){
			if($repeat==0 && $rs['code'] == '0002'){
				$newordernum = date('YmdHis').rand(100000,999999);
				Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
				if($tablename == 'shop_hb'){
					Db::name('shop_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					$orderlist = Db::name('shop_order')->where('ordernum','like',$ordernum.'%')->select()->toArray();
					foreach($orderlist as $order){
						$thisordernum = $newordernum.'_'.explode('_',$order['ordernum'])[1];
						Db::name('shop_order')->where('aid',$aid)->where('id',$order['id'])->update(['ordernum'=>$thisordernum]);
						Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['ordernum'=>$thisordernum]);
					}
				}else{
					Db::name($tablename.'_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					if($tablename == 'shop' || $tablename == 'scoreshop' || $tablename == 'restaurant_shop' || $tablename == 'restaurant_booking'){
						Db::name($tablename.'_order_goods')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					}
				}
				return self::build_wx($aid,$bid,$mid,$title,$newordernum,$price,$tablename,$notify_url,1);
			}
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		$respData = $rs['respData'];
		$wOpt = [];
		$wOpt['appId'] = $respData['payAppId'];
		$wOpt['timeStamp'] = $respData['payTimeStamp'];
		$wOpt['nonceStr'] = $respData['paynonceStr'];
		$wOpt['package'] = $respData['payPackage'];
		$wOpt['signType'] = $respData['paySignType'];
		$wOpt['paySign'] = $respData['paySign'];

		return ['status'=>1,'data'=>$wOpt];
	}

	//创建支付 支付宝小程序
	public static function build_alipay($aid,$bid,$mid,$title,$ordernum,$price,$tablename,$notify_url=''){
		if(!$notify_url) $notify_url = PRE_URL.'/notify.php';
		$member = Db::name('member')->where('id',$mid)->find();
		$package = array();
		$appinfo = \app\common\System::appinfo($aid,'alipay');
		$isbusinesspay = false;
		if($bid > 0){
			$business = Db::name('business')->where('id',$bid)->find();
			if($business['sxpay_mno']){
				$appinfo['sxpay_mno'] = $business['sxpay_mno'];
				$appinfo['sxpay_mchkey'] = $business['sxpay_mchkey'];
				$isbusinesspay = true;
			}
		}
		$appid = $appinfo['appid'];
		$openid = $member['alipayopenid'];
		if(!$appinfo['sxpay_mno']){
			return ['status'=>0,'msg'=>'请设置商户编号'];
		}
		if(!$appinfo['sxpay_mchkey']){
			return ['status'=>0,'msg'=>'请设置支付密钥'];
		}
		
		$reqData = [];
		$reqData['mno'] = $appinfo['sxpay_mno']; //商户编号
		$reqData['ordNo'] = $ordernum; //商户订单号
		$reqData['amt'] = $price;
		$reqData['payType'] = 'ALIPAY';
		$reqData['payWay'] = '02';
		$reqData['subject'] = $title;
		$reqData['trmIp'] = request()->ip();
		$reqData['notifyUrl'] = $notify_url;
		$reqData['userId'] = $openid;
		$reqData['extend'] = $aid.':'.$tablename.':sxpayalipay:'.md5($tablename.$ordernum.$appinfo['sxpay_mchkey']);
		if($isbusinesspay) $reqData['extend'] .= ':'.$bid;

		$fenzhang = Db::name('sxpay_fenzhang')->where('aid',$aid)->where('business_code',$reqData['mno'])->where('status',1)->find();
		if($fenzhang){
			$fenzhangdata = json_decode($fenzhang['fenzhangdata'],true);
			if($fenzhangdata){
				$fusruleId = [];
				foreach($fenzhangdata as $fz){
					$fzpercent = floatval($fz['percent']);
					$fzprice = round($fzpercent * 0.01 * $reqData['amt'],2);
					if($fzprice > 0){
						$fusruleId[] = ['allotValue'=>$fzprice,'mno'=>$fz['business_code']];
					}
				}
				if($fusruleId){
					$reqData['fusruleId'] = $fusruleId;
				}
			}
		}
		//\think\facade\Log::write($reqData);

		Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['issxpay'=>1,'createtime'=>time()]);

		$rs = self::postapi('build',$reqData,$appinfo['sxpay_mchkey']);

		if($rs['code'] != '0000'){
			if($repeat==0 && $rs['code'] == '0002'){
				$newordernum = date('YmdHis').rand(100000,999999);
				Db::name('payorder')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
				if($tablename == 'shop_hb'){
					Db::name('shop_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					$orderlist = Db::name('shop_order')->where('ordernum','like',$ordernum.'%')->select()->toArray();
					foreach($orderlist as $order){
						$thisordernum = $newordernum.'_'.explode('_',$order['ordernum'])[1];
						Db::name('shop_order')->where('aid',$aid)->where('id',$order['id'])->update(['ordernum'=>$thisordernum]);
						Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['ordernum'=>$thisordernum]);
					}
				}else{
					Db::name($tablename.'_order')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					if($tablename == 'shop' || $tablename == 'scoreshop' || $tablename == 'restaurant_shop' || $tablename == 'restaurant_booking'){
						Db::name($tablename.'_order_goods')->where('aid',$aid)->where('ordernum',$ordernum)->update(['ordernum'=>$newordernum]);
					}
				}
				return self::build_alipay($aid,$bid,$mid,$title,$newordernum,$price,$tablename,$notify_url,1);
			}
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		$respData = $rs['respData'];
		$wOpt = [];
		$wOpt['trade_no'] = $respData['source'];

		return ['status'=>1,'data'=>$wOpt,'$respData'=>$respData];
	}

	//查询订单
	public static function tradeQuery($payorder){

		$appinfo = \app\common\System::appinfo($payorder['aid'],$payorder['platform']);
		$reqData = [];
		$reqData['mno'] = $appinfo['sxpay_mno']; //商户编号
		$reqData['ordNo'] = $payorder['ordernum']; //订单号

		$rs = self::postapi('tradeQuery',$reqData,$appinfo['sxpay_mchkey']);

		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'查询成功','data'=>$rs['respData']];
	}

	//退款
	public static function refund($aid,$platform,$ordernum,$totalprice,$refundmoney,$refund_desc='退款'){
		$appinfo = \app\common\System::appinfo($aid,$platform);
		$reqData = [];
		$reqData['mno'] = $appinfo['sxpay_mno']; //商户编号
		$reqData['origOrderNo'] = $ordernum;
		$reqData['ordNo'] = $ordernum. '_' . rand(1000, 9999); //商户订单号
		$reqData['amt'] = $refundmoney;
		$reqData['refundReason'] = $refund_desc;

		$rs = self::postapi('refund',$reqData,$appinfo['sxpay_mchkey']);

		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		
		//记录
		$data = [];
		$data['aid'] = $aid;
		$data['mch_id'] = $appinfo['sxpay_mno'];
		$data['ordernum'] = $ordernum;
		$data['out_refund_no'] = $reqData['ordNo'];
		$data['totalprice'] = $totalprice;
		$data['refundmoney'] = $refundmoney;
		$data['createtime'] = date('Y-m-d H:i:s');
		$data['status'] = 1;
		$data['remark'] = $refund_desc;
		Db::name('wxrefund_log')->insert($data);

		$paylog = Db::name('wxpay_log')->where('aid',$aid)->where('ordernum',$ordernum)->find();
		if($paylog){
			Db::name('wxpay_log')->where('id',$paylog['id'])->inc('refund_money',$refundmoney)->update();
		}
		return ['status'=>1,'msg'=>'退款成功','resp'=>$rs['respData']];
	}

	//商户入驻
	public static function income($reqData){
		$rs = self::postapi('income',$reqData);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'提交成功','data'=>$rs['respData']];
	}
	//商户修改
	public static function modify($reqData,$mchkey){
		$rs = self::postapi('modify',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'提交成功','data'=>$rs['respData']];
	}
	//入驻结果查询
	public static function applyQuery($reqData,$mchkey){
		$rs = self::postapi('applyQuery',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'查询成功','data'=>$rs['respData']];
	}
	//修改结果查询
	public static function modifyQuery($reqData,$mchkey){
		$rs = self::postapi('modifyQuery',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'查询成功','data'=>$rs['respData']];
	}

	//设置微信子商户参数
	public static function addConf($reqData,$mchkey){
		$rs = self::postapi('addConf',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'设置成功'];
	}
	//查看配置 
	public static function viewConf($reqData,$mchkey){
		$rs = self::postapi('viewConf',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'设置成功','data'=>$rs['respData']];
	}
	//签署协议
	public static function signxieyi($reqData,$mchkey){
		$rs = self::postapi('signxieyi',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'设置成功','signUrl'=>$rs['respData']['signUrl']];
	}
	//实名认证
	public function shiming($reqData,$mchkey){
		$rs = self::postapi('shiming',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'提交成功,请等待审核'];
	}
	//实名认证查询
	public function shimingQuery($reqData,$mchkey){
		$rs = self::postapi('shimingQuery',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'查询成功','data'=>$rs['respData']];
	}
	//生成密钥
	public static function updateMchkey($reqData,$mchkey){
		$rs = self::postapi('updateMchkey',$reqData,$mchkey);
		return $rs;
	}
	//获取银行列表
	public static function getjiesuanbanklist($reqData){
		$rs = self::postapi('getjiesuanbanklist',$reqData);
		return $rs;
	}
	//获取省市区编码
	public static function getareacode($reqData){
		$rs = self::postapi('getareacode',$reqData);
		return $rs;
	}
	
	public static function signxieyifz($reqData,$mchkey){
		$rs = self::postapi('signxieyifz',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'设置成功','retUrl'=>$rs['respData']['retUrl']];
	}
	public static function setMnoArrayfz($reqData,$mchkey){
		$rs = self::postapi('setMnoArrayfz',$reqData,$mchkey);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return ['status'=>1,'msg'=>'设置成功'];
	}

	//上传图片
	public static function uploadimg($picurl,$type){
		$url = 'https://openapi.tianquetech.com/merchant/uploadPicture';
		$data = [];
		$dbsxpayset = Db::name('sysset')->where('name','sxpayset')->value('value');
		$dbsxpayset = json_decode($dbsxpayset,true);
		if($dbsxpayset && $dbsxpayset['orgId']){
			$data['orgId'] = $dbsxpayset['orgId'];
		}else{
			$data['orgId'] = '52439584';
		}
		$data['reqId'] = random(16);
		$data['pictureType'] = $type;

		$picurl = \app\common\Pic::tolocal($picurl);
		$picpath = ROOT_PATH.str_replace(PRE_URL.'/','',$picurl);

		$data['file'] = new \CurlFile($picpath);
		$header = ["content-type:multipart/form-data"];
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url);
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

		$info = curl_exec ( $ch );
		if (curl_errno ( $ch )) {
			return ['status'=>0,'msg'=>curl_error($ch)];
		}
		curl_close ( $ch );
		$rs = json_decode($info,true);
		if($rs['code'] != '0000'){
			return ['status'=>0,'msg'=>$rs['msg']];
		}
		if($rs['respData']['bizCode'] != '0000'){
			return ['status'=>0,'msg'=>$rs['respData']['bizMsg']];
		}
		return $rs['respData']['PhotoUrl'];
	}

	public static function postapi($action,$reqData,$mchkey=''){
		
		if(!in_array($action,['getjiesuanbanklist','getareacode'])){
			$dbsxpayset = Db::name('sysset')->where('name','sxpayset')->value('value');
			$dbsxpayset = json_decode($dbsxpayset,true);
			if($dbsxpayset && $dbsxpayset['orgId']){
				if($action == 'updateMchkey'){
					$newmchkey = strtolower(random(32));
					Db::name('sxpay_income')->where('business_code',$reqData['business_code'])->update(['mchkey'=>$newmchkey]);
					return ['status'=>1,'data'=>['mchkey'=>$newmchkey]];
				}
				if($action == 'income'){
					$reqData['qrcodeList'] = [['rateType'=>'01','rate'=>$dbsxpayset['feepercent']],['rateType'=>'02','rate'=>$dbsxpayset['feepercent']],['rateType'=>'06','rate'=>$dbsxpayset['feepercent']],['rateType'=>'07','rate'=>'0.6']];
				}
				$rs = self::curlpost($action,$reqData,$dbsxpayset['orgId'],$dbsxpayset['privateKey'],$dbsxpayset['signType']);
				$rs = json_decode($rs,true);
				if($action == 'income'){
					if($rs['code'] == '0000' && $rs['respData']['bizCode'] == '0000'){
						$rs['respData']['mchkey'] = strtolower(random(32));
					}
				}
				return $rs;
			}
		}

		if($mchkey){
			ksort($reqData);
			$string1 = '';
			foreach ($reqData as $key => $v) {
				if(is_array($v)){
					$string1 .= "{$key}=".json_encode($v)."&";
				}else{
					$string1 .= "{$key}={$v}&";
				}
			}
			$string1 .= "key=".$mchkey;
			$reqData['sign'] = strtoupper(md5($string1));
		}

		$rs = curl_post('https://pay.diandashop.com/?s=Api/'.$action,['data'=>json_encode($reqData)]);
		$rs = json_decode($rs,true);
		return $rs;
	}

	public static function curlpost($apipath,$reqData,$orgId,$privateKey,$signType){
		$apiArr = [
			'income'=>'/merchant/income',
			'modify'=>'/merchant/editMerchantInfo',
			'applyQuery'=>'/merchant/queryMerchantInfo',
			'modifyQuery'=>'/merchant/queryModifyResult',
			'addConf'=>'/merchant/weChatPaySet/addConf',
			'viewConf'=>'/merchant/weChatPaySet/queryConf',
			'signxieyi'=>'/merchant/elecSignature/openElecSignature',
			'shiming'=>'/merchant/realName/commitApply',
			'shimingQuery'=>'/merchant/realName/queryApplyInfo',
			'build'=>'/order/jsapiScan',
			'tradeQuery'=>'/query/tradeQuery',
			'refund'=>'/order/refund',
			'signxieyifz'=>'/merchant/sign/getUrl',
			'setMnoArrayfz'=>'/query/ledger/setMnoArray',
		];
		$url = 'https://openapi.tianquetech.com'.$apiArr[$apipath];
		$data = self::sign($reqData,$orgId,$privateKey,$signType);
		$reqStr = json_encode($data);
		$rs = curl_post($url,$reqStr,0,['content-type:application/json;charset=UTF-8']);
		return $rs;
	}
	public static function sign($reqData,$orgId,$privateKey, $signType = "RSA"){
		if(!$signType) $signType = 'RSA';
		$data = [];
		$data['signType'] = $signType;
		$data['version'] = '1.0';
		$data['orgId'] = $orgId;
		$data['reqId'] = random(16);
		$data['reqData'] = $reqData;
		$data['timestamp'] = date('YmdHis');
		$rsaPriKeyStr = $privateKey;

		ksort($data);
        $stringToBeSigned = "";
        foreach($data as $k => $v){
            $isarray = is_array($v);
            if ($isarray) {
                $stringToBeSigned .= "$k" . "=" . json_encode($v, 320) . "&";
            } else {
                $stringToBeSigned .= "$k" . "=" . "$v" . "&";
            }
        }
        unset ($k, $v);
        $stringToBeSigned = substr($stringToBeSigned, 0, strlen($stringToBeSigned) - 1);

         $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($rsaPriKeyStr, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');

        if ("RSA2" == $signType) {
            openssl_sign($stringToBeSigned, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($stringToBeSigned, $sign, $res);
        }
        $data['sign'] = base64_encode($sign);
        return $data;
    }
}